package com.exam.controller;

import com.exam.domain.Field;
import com.exam.domain.Grade;
import com.exam.domain.Question;
import com.exam.domain.Strategies;
import com.exam.service.interfaces.QuestionService;
import com.exam.service.interfaces.StudentExamService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * Created by jly on 2017/3/3.
 */
@Controller
@RequestMapping("/studentExamController")
public class StudentExamController {
    @Resource
    private StudentExamService studentExamService;
    @Resource
    private QuestionService questionService;

    /**
     * 进入学生考试界面
     *
     * @return: 进入学生考试界面
     * @since: 2017-3-6
     * @author: jly
     */
    @RequestMapping("/studentExamView")
    public String studentExamView(HttpServletRequest request) {
        if (request.getSession().getAttribute("userName") == null) {
            return "redirect:" + UserController.basePath(request);
        }
        return "studentexam/startexam";
    }

    /**
     * 查询所有科目
     *
     * @return: 返回数据库科目表所有内容
     * @Since: 2017-2-13
     * @author: jly
     */
    @RequestMapping("/fields")
    @ResponseBody
    public List<Field> allFields() {
        return questionService.queryFields();
    }

    /**
     * 随机试题组卷
     *
     * @return: 试题列表(选择题)
     * @since: 2017-3-6
     * @author: jly
     */
    @RequestMapping("/studentExam")
    @ResponseBody
    public List<Question> studentExam(Integer fieldid) {
        Integer count = studentExamService.queryQCount(fieldid, 1, 1);
        Integer count2 = studentExamService.queryQCount(fieldid, 1, 2);
        Integer count3 = studentExamService.queryQCount(fieldid, 1, 3);
        List<Question> examList = new ArrayList<>();
        if (count != null) {
            List<Question> list1 = studentExamService.studentExam(fieldid, count, "1");
            for (int i = 0; i < list1.size(); i++) {
                examList.add(list1.get(i));
            }
        }
        if (count2 != null) {
            List<Question> list2 = studentExamService.studentExam(fieldid, count2, "2");
            for (int i = 0; i < list2.size(); i++) {
                examList.add(list2.get(i));
            }
        }
        if (count3 != null) {
            List<Question> list3 = studentExamService.studentExam(fieldid, count3, "3");
            for (int i = 0; i < list3.size(); i++) {
                examList.add(list3.get(i));
            }
        }
        return examList;
    }

    /**
     * 随机试题组卷
     *
     * @return: 试题列表(判断题)
     * @since: 2017-3-6
     * @author: jly
     */
    @RequestMapping("/studentExam2")
    @ResponseBody
    public List<Question> studentExam2(Integer fieldid) {
        Integer count = studentExamService.queryQCount(fieldid, 2, 1);
        Integer count2 = studentExamService.queryQCount(fieldid, 2, 2);
        Integer count3 = studentExamService.queryQCount(fieldid, 2, 3);
        List<Question> examList = new ArrayList<>();
        if (count != null) {
            List<Question> list1 = studentExamService.studentExam2(fieldid, count, "1");
            for (int i = 0; i < list1.size(); i++) {
                examList.add(list1.get(i));
            }
        }
        if (count2 != null) {
            List<Question> list2 = studentExamService.studentExam2(fieldid, count2, "2");
            for (int i = 0; i < list2.size(); i++) {
                examList.add(list2.get(i));
            }
        }
        if (count3 != null) {
            List<Question> list3 = studentExamService.studentExam2(fieldid, count3, "3");
            for (int i = 0; i < list3.size(); i++) {
                examList.add(list3.get(i));
            }
        }
        return examList;
    }

    /**
     * 随机试题组卷
     *
     * @return: 试题列表(填空题)
     * @since: 2017-3-17
     * @author: jly
     */
    @RequestMapping("/studentExam3")
    @ResponseBody
    public List<Question> studentExam3(Integer fieldid) {
        Integer count = studentExamService.queryQCount(fieldid, 3, 1);
        Integer count2 = studentExamService.queryQCount(fieldid, 3, 2);
        Integer count3 = studentExamService.queryQCount(fieldid, 3, 3);
        List<Question> examList = new ArrayList<>();
        if (count != null) {
            List<Question> list1 = studentExamService.studentExam3(fieldid, count, "1");
            for (int i = 0; i < list1.size(); i++) {
                examList.add(list1.get(i));
            }
        }
        if (count2 != null) {
            List<Question> list2 = studentExamService.studentExam3(fieldid, count2, "2");
            for (int i = 0; i < list2.size(); i++) {
                examList.add(list2.get(i));
            }
        }
        if (count3 != null) {
            List<Question> list3 = studentExamService.studentExam3(fieldid, count3, "3");
            for (int i = 0; i < list3.size(); i++) {
                examList.add(list3.get(i));
            }
        }
        return examList;
    }

    /**
     * 随机试题组卷
     *
     * @return: 试题列表(主观题)
     * @since: 2017-3-17
     * @author: jly
     */
    @RequestMapping("/studentExam4")
    @ResponseBody
    public List<Question> studentExam4(Integer fieldid) {
        Integer count;
        Integer count2;
        Integer count3;
        List<Question> examList = new ArrayList<>();
        List<Strategies> strategies = studentExamService.queryZGTcount(fieldid);
        int[] typeId = new int[strategies.size()];
        for (int i = 0; i < strategies.size(); i++) {
            typeId[i] = strategies.get(i).getQuestionTypeId();
        }
        for (int j = 0; j < typeId.length; j++) {
            count = studentExamService.queryQCount(fieldid, typeId[j], 1);
            count2 = studentExamService.queryQCount(fieldid, typeId[j], 2);
            count3 = studentExamService.queryQCount(fieldid, typeId[j], 3);
            if (count != null) {
                List<Question> list1 = studentExamService.studentExam4(fieldid, typeId[j], count, "1");
                for (int i = 0; i < list1.size(); i++) {
                    examList.add(list1.get(i));
                }
            }
            if (count2 != null) {
                List<Question> list2 = studentExamService.studentExam4(fieldid, typeId[j], count2, "2");
                for (int i = 0; i < list2.size(); i++) {
                    examList.add(list2.get(i));
                }
            }
            if (count3 != null) {
                List<Question> list3 = studentExamService.studentExam4(fieldid, typeId[j], count3, "3");
                for (int i = 0; i < list3.size(); i++) {
                    examList.add(list3.get(i));
                }
            }
        }
        return examList;
    }

    /**
     * 提交试卷
     *
     * @return 0-成功，1-失败
     * @author jly
     * @since 2017-3-6
     */
    @RequestMapping(value = "/submitPaper", method = RequestMethod.POST)
    @ResponseBody
    public int submitPaper(@RequestParam(value = "qId[]") String qId,
                           @RequestParam(value = "qAnswer[]") String qAnswer,
                           @RequestParam(value = "zgtId[]") String zgtId,
                           Integer field, HttpSession session) throws ParseException {
        zgtId = zgtId.trim();
        zgtId = zgtId.replaceAll("\n","");
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowtime = dateFormat.format(now);
        String strattime = Time(nowtime);
        int result = 0;
        int grade = 0;
        boolean addGrade;
        boolean addteachergrade = false;
        int rank = 0;
        Long userid = (Long) session.getAttribute("userId");
        String[] questionid = qId.split(",");
        qAnswer = qAnswer.replaceAll("/", "");
        String[] questioanswer = qAnswer.split(",");
        String[] zgtIds = zgtId.split("&");
        for (int i = 0; i < questionid.length; i++) {
            //数据库的正确答案
            String dbAnswer = studentExamService.queryAnswer(Integer.valueOf(questionid[i]));
            //选择的答案和数据库答案比较
            if (questioanswer[i].contains(dbAnswer)) {
                grade += 2;
            }
            if (i == questionid.length - 1) {
                if (grade >= 85) {
                    rank = 1;
                } else if (grade >= 75 && grade < 85) {
                    rank = 2;
                } else if (grade >= 60 && grade < 75) {
                    rank = 3;
                } else if (grade < 60) {
                    rank = 4;
                }
                addGrade = studentExamService.addGrade(userid, field, rank, grade, nowtime, strattime);
                int maxgradeId = studentExamService.queryMaxgradeId();
                for (int j = 0; j < zgtIds.length; j++) {
                    String[] tip1 = zgtIds[j].split(",");
                   if(tip1.length == 3){
                       if(tip1[2].equals("") || tip1[2] == null){
                           tip1[2] = " ";
                       }
                       addteachergrade =
                               studentExamService.addteachergrade(Integer.valueOf(tip1[1]),
                                       maxgradeId,grade,strattime,tip1[2]);
                   }
                   else {
                       if(tip1[1].equals("") || tip1[1] == null){
                           tip1[1] = " ";
                       }
                       addteachergrade =
                               studentExamService.addteachergrade(Integer.valueOf(tip1[0]),
                                       maxgradeId,grade,strattime,tip1[1]);
                   }
                }
                if (addGrade && addteachergrade) {
                    result = 1;
                    break;
                } else {
                    result = 0;
                    break;
                }
            } else {
                continue;
            }
        }
        return result;
    }

    /**
     * 进入学生成绩统计界面
     *
     * @return: 进入学生成绩统计界面
     * @since: 2017-3-6
     * @author: jly
     */
    @RequestMapping("/gradeStatisticView")
    public String gradeStatisticView(HttpServletRequest request, Model model) {
        if (request.getSession().getAttribute("userName") == null) {
            return "redirect:" + UserController.basePath(request);
        }
        Long userId = (Long) request.getSession().getAttribute("userId");
        List<Grade> grades = studentExamService.studentGrades(userId);
        String fields = "";
        String grade2 = "";
        for (int i = 0; i < grades.size(); i++) {
            fields += "'" + grades.get(i).getField().getFieldName() + "',";
            grade2 += grades.get(i).getGrade() + ",";
        }
        model.addAttribute("fields", fields);
        model.addAttribute("grade2", grade2);
        return "studentexam/gradestatistic";
    }

    /**
     * 加载学生成绩列表（登录角色为学生）
     *
     * @return Grade类型的成绩详细信息
     * @author jly
     * @since 2017-3-8
     */
    @RequestMapping("/List")
    @ResponseBody
    public List<Grade> studentGrades(HttpSession session) {
        Long userId = (Long) session.getAttribute("userId");
        List<Grade> grades = studentExamService.studentGrades(userId);
        return grades;
    }


    public static String Time(String time) throws ParseException {
        Date rtn = null;
        Date date2 = null;
        GregorianCalendar cal = new GregorianCalendar();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        date2 = sdf.parse(time);
        Long dLong = date2.getTime();
        Date date = new Date(dLong);
        cal.setTime(date);
        cal.add(12, 100);
        rtn = cal.getTime();
        String a = sdf.format(rtn);
        System.out.println("=========================" + a);
        return a;
    }
}
